package com.itheima.tlias08_14.exception;


import com.itheima.tlias08_14.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.StringJoiner;

/**
 * 由于trycatch只能捕获
 *全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(ArithmeticException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultUtil handleArithmeticException(ArithmeticException e){
        return ResultUtil.failure(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultUtil handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        log.info("bindingResult为:{}", bindingResult);
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        log.info("fieldErrors为:{}", fieldErrors);
        StringJoiner stringJoiner = new StringJoiner( ",","[","]");
        //利用StringJoiner将获取到的错误信息拼接成字符串
        int i = 1;
        for(FieldError fieldError :fieldErrors){
            log.info("fieldError{}为:{}",i++, fieldError);
            stringJoiner.add(fieldError.getDefaultMessage());
        }
        return ResultUtil.failure(stringJoiner.toString());
    }
}
